package com.bootdo.xzl.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.common.utils.UploadUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.xzl.dao.BuildingManagementDao;
import com.bootdo.xzl.dao.HousesImgInfoDao;
import com.bootdo.xzl.domain.BuildingManagementDO;
import com.bootdo.xzl.domain.HousesImgInfoDO;
import com.bootdo.xzl.domain.HousesImgInfoDO2;
import com.bootdo.xzl.service.BuildingManagementService;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;



@Service
public class BuildingManagementServiceImpl implements BuildingManagementService {
	
	@Value("${file.path}")
	private String filePath;
	
	@Autowired
	private BuildingManagementDao buildingManagementDao;
	
	@Autowired
	private HousesImgInfoDao housesImgInfoDao;
	
	@Override
	public BuildingManagementDO get(Integer id){
		return buildingManagementDao.get(id);
	}
	
	@Override
	public List<BuildingManagementDO> list(Map<String, Object> map){
		return buildingManagementDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return buildingManagementDao.count(map);
	}
	
	@Override
	public int save(BuildingManagementDO buildingManagement){
		String indexradioFile="";
		try {
		//根据索引获取文件名
		 // 获取关联文件
		 List<MultipartFile> files =  buildingManagement.getFiles();
		 if(files!=null) {
			 if("".equals(buildingManagement.getIndexradio())) {
				 buildingManagement.setIndexradio("0");
				 
				 indexradioFile = afterUploadFileName(files.get(0).getOriginalFilename());
			 }else {
				 indexradioFile = afterUploadFileName(files.get(Integer.parseInt(buildingManagement.getIndexradio())).getOriginalFilename());
			 }		
			 buildingManagement.setIndexfile(indexradioFile);
		 }else {
			 buildingManagement.setIndexradio("");
			 buildingManagement.setIndexfile("");
		 }
		
	     // 用户信息
		UserDO user = ShiroUtils.getUser();
		 if(null!=user.getUserId()){
			 buildingManagement.setUpdateBy(user.getUserId()+"");
			 buildingManagement.setUpdateDate(DateUtils.getSysDate());
			 buildingManagement.setTel(user.getMobile());
			 buildingManagement.setTelname(user.getName());
		 }
		 buildingManagementDao.save(buildingManagement);
		 
		   if(null!=buildingManagement && null!=buildingManagement.getFiles() && buildingManagement.getFiles().size()>0){
				
				 int max = files.size();
				 List<HousesImgInfoDO> images =  new ArrayList<>(max);
				 HousesImgInfoDO housesImgInfoDO =  null;

			     for(int i=0;i<max;i++){
				         
						 housesImgInfoDO = new HousesImgInfoDO();
						 // 房源id
						 housesImgInfoDO.setOfficeId(buildingManagement.getId());
						 // 房源编号
						 housesImgInfoDO.setOfficeHousesNumber(generatePrimarykey());
						 // 图片编号
						 housesImgInfoDO.setImgNo(generatePrimarykey());
						 // 上传文件名
						 housesImgInfoDO.setFileName(files.get(i).getOriginalFilename());
						 // 磁盘物理文件名
						 String physicalFileName = afterUploadFileName(files.get(i).getOriginalFilename());
						 if(i==Integer.parseInt(buildingManagement.getIndexradio())) {
							 housesImgInfoDO.setPhysicalFileName(indexradioFile);
						 }else {
							 housesImgInfoDO.setPhysicalFileName(physicalFileName);
						 }
		
						 // 上传人
						 if(null!=buildingManagement.getUserId()){
							 housesImgInfoDO.setCreateBy(String.valueOf(buildingManagement.getUserId()));
						 }
						 // 文件类型
						 String filetype = getSuffixName(files.get(i).getOriginalFilename());
						 housesImgInfoDO.setFileType(filetype);
						 //文件大小
						 housesImgInfoDO.setFileSize(files.get(i).getSize());
					 
						//业务类型
						housesImgInfoDO.setImgFlg("2");
						// 获取水印图片
						InputStream inputImg = files.get(i).getInputStream();
						BufferedImage image = ImageIO.read(inputImg);

						 Thumbnails.of(image).size(800,600).watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(filePath+"logo.png")), 0.4f)
					        .outputQuality(0.6f).toFile(filePath+housesImgInfoDO.getPhysicalFileName());
	
						// 添加集合
						images.add(housesImgInfoDO);
			 }	 					 
		 housesImgInfoDao.save(images);

	}
	} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}
	
	@Override
	public int update(BuildingManagementDO buildingManagement){
		 // 获取关联文件
		 List<MultipartFile> files =null;
		 List<HousesImgInfoDO> images =null;
		 List<HousesImgInfoDO2> lstimages = new ArrayList<HousesImgInfoDO2>();
		 HousesImgInfoDO2 housesImgInfoDO2 =null;
		 if(buildingManagement.getComonefiles()!=null) {
			    for(int i=0;i<buildingManagement.getComonefiles().size();i++) {
					 
					 housesImgInfoDO2 = JSON.parseObject(buildingManagement.getComonefiles().get(i), HousesImgInfoDO2.class);
					 lstimages.add(housesImgInfoDO2);
				 }
		 }
	 

	     // 用户信息
		UserDO user = ShiroUtils.getUser();
		 if(null!=user.getUserId()){
			 buildingManagement.setUpdateBy(user.getUserId()+"");
			 buildingManagement.setUpdateDate(DateUtils.getSysDate());
			 buildingManagement.setTel(user.getMobile());
			 buildingManagement.setTelname(user.getName());
		 }

			try {
				
				// 删除磁盘文件
				if(null!=buildingManagement && buildingManagement.getDelImagesIds()!=null && buildingManagement.getDelImagesIds().size()>0){
						// 查询文件列表
					   Integer[] array =  buildingManagement.getDelImagesIds().toArray(new  Integer[buildingManagement.getDelImagesIds().size()]);
					   images = housesImgInfoDao.getImgListByIds(array);
					   if(null!=images && images.size()>0 ){
						    int max = images.size();
						    // 删除磁盘文件
						    File file  = null;
						   for(int i=0;i<max;i++){
							   file = new File(filePath+images.get(i).getPhysicalFileName());
							   if(file.exists()){
								   file.delete();
							   }
						   }
					   }
					 //删除数据库文件

					 housesImgInfoDao.batchUpdate(images);
				}
				
				// 上传文件
				if(null!=buildingManagement && null!=buildingManagement.getFiles() && buildingManagement.getFiles().size()>0){
						 // 获取关联文件
						 files =  buildingManagement.getFiles();
						 int max = files.size();
						 images =  new ArrayList<>(max);
						 HousesImgInfoDO housesImgInfoDO =  null;
					
					 for(int i=0;i<max;i++){
								 housesImgInfoDO = new HousesImgInfoDO();
								 // 房源id
								 housesImgInfoDO.setOfficeId(buildingManagement.getId());
								 // 房源编号	
								 housesImgInfoDO.setOfficeHousesNumber(generatePrimarykey());
								 // 图片编号
								 housesImgInfoDO.setImgNo(generatePrimarykey());
								 // 上传文件名
								 housesImgInfoDO.setFileName(files.get(i).getOriginalFilename());
								 // 磁盘物理文件名
								 String physicalFileName = afterUploadFileName(files.get(i).getOriginalFilename());
								 housesImgInfoDO.setPhysicalFileName(physicalFileName);
								 // 上传人
								 if(null!=buildingManagement.getUserId()){
									 housesImgInfoDO.setCreateBy(String.valueOf(buildingManagement.getUserId()));
								 }
								 // 文件类型
								 String filetype = getSuffixName(files.get(i).getOriginalFilename());
								 housesImgInfoDO.setFileType(filetype);
								 //文件大小
								 housesImgInfoDO.setFileSize(files.get(i).getSize());
								 // 上传文件
								//业务类型
								housesImgInfoDO.setImgFlg("2");
								// 获取水印图片
								InputStream inputImg = files.get(i).getInputStream();
								BufferedImage image = ImageIO.read(inputImg);

								 Thumbnails.of(image).size(800,600).watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(filePath+"logo.png")), 0.4f)
							        .outputQuality(0.6f).toFile(filePath+housesImgInfoDO.getPhysicalFileName());
								// 添加集合
								images.add(housesImgInfoDO);
					 }
					 housesImgInfoDao.save(images);
				}
				
				
				//根据索引获取文件名
	            //1.没有删除文件操作只有上传文件操作。
				if(buildingManagement.getDelImagesIds()==null && null!=buildingManagement.getFiles() && buildingManagement.getFiles().size()>0) {
					if(Integer.parseInt(buildingManagement.getDatalength())>=Integer.parseInt(buildingManagement.getBeforedatalength())) {
						if(!"".equals(buildingManagement.getIndexradio())) {
							Integer c =Integer.parseInt(buildingManagement.getIndexradio())-Integer.parseInt(buildingManagement.getBeforedatalength());
							String filename = images.get(c).getPhysicalFileName();
							buildingManagement.setIndexfile(filename);
						}else {
							buildingManagement.setIndexradio("0");
							String filename = images.get(0).getPhysicalFileName();
							buildingManagement.setIndexfile(filename);
						}
					}
				}
	            //2.没有上传文件操作只有删除文件操作
				if(buildingManagement.getDelImagesIds()!=null &&null==buildingManagement.getFiles()) {
					if(Integer.parseInt(buildingManagement.getIndexradio())>=Integer.parseInt(buildingManagement.getDatalength())) {
					
						Integer c =Integer.parseInt("0");
						String filename = lstimages.get(c).getPhysicalFileName();
						buildingManagement.setIndexradio("0");
						buildingManagement.setIndexfile(filename);
					}else {
						Integer c =Integer.parseInt(buildingManagement.getIndexradio());
						String filename = lstimages.get(c).getPhysicalFileName();
						buildingManagement.setIndexfile(filename);
					}
				}
	            //3.既有删除文件操作又有上传文件操作。
				if(buildingManagement.getDelImagesIds()!=null && null!=buildingManagement.getFiles() && buildingManagement.getFiles().size()>0) {

						Integer c =Integer.parseInt(buildingManagement.getIndexradio())-(Integer.parseInt(buildingManagement.getBeforedatalength())-buildingManagement.getDelImagesIds().size());
						String filename = images.get(c).getPhysicalFileName();
						buildingManagement.setIndexfile(filename);

				}
				 // 修改人
				 if(null!=buildingManagement.getUserId()){
					 buildingManagement.setUpdateBy(String.valueOf(buildingManagement.getUserId()));
				 }
				 buildingManagement.setUpdateDate(DateUtils.getSysDate());
				
				
				 buildingManagementDao.update(buildingManagement);
		 	 
	} catch (Exception e) {
		e.printStackTrace();
		return 0;
	}
	return 1;
	}
	
	@Override
	public int batchUpdate(Integer[] ids) {
		// TODO Auto-generated method stub
		return buildingManagementDao.batchUpdate(ids);
	}
	
	@Override
	public int remove(Integer id){
		return buildingManagementDao.remove(id);
	}
	
	@Override
	public int batchRemove(Integer[] ids){
		return buildingManagementDao.batchRemove(ids);
	}
	
   //获取文件后缀名
	public String getSuffixName(String fileName) {
		if (StringUtils.isEmpty(fileName)) {
			return "";
		} else if (fileName.indexOf(fileName) < 0) {
			return "";
		}
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		return suffix;
	}
		
	
	// 获取上传后的文件名
	public String afterUploadFileName(String type) {
		if (StringUtils.isEmpty(type)) {
			return "";
		}
		long r = (long) ((Math.random() * 9 + 1) * 100000);
		long s = Calendar.getInstance().getTimeInMillis();
		String t = String.valueOf(r) + String.valueOf(s) + UploadUtils.getSuffixName(type);
		
		return t;
	}
	public String generatePrimarykey() {
		long r = (long) ((Math.random() * 9 + 1) * 10000000);
		long s = Calendar.getInstance().getTimeInMillis();
		String key = String.valueOf(r) + String.valueOf(s);
		return key;
	}

	@Override
	public BuildingManagementDO getBuilding(Integer id) {
		BuildingManagementDO  buildingManagementDO = buildingManagementDao.get(id);
	    if(buildingManagementDO !=null) {
	    	// 查询文件列表
			   Integer[] array =  new Integer[1];
			   array[0] = id;
			   List<HousesImgInfoDO> imagesLst = housesImgInfoDao.getImgListByofficeId(array,"2");
			   buildingManagementDO.setHousesImgInfoList(imagesLst);
	    }
		return buildingManagementDO;
	}
}
